/*
*
* 根据名称获取url参数
* window.location.search 获取地址栏内的 ？后面的一串字符串 index.php?act=doctor,截取后的字符串就是act=doctor
*/
function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if (r && r[2]) return decodeURIComponent(r[2]); return null;
}


/*
*
* 对String对象添加toJson方法
*
*/
String.prototype.toJson=function(){
	return (new Function("return " + this))();
};

// 日期格式转换
function ChangeDateFormat(val) {
	if (val) {
		//if(val.indexOf('-')>-1){ return '';}
		//var date = new Date(parseInt(val.replace("/Date(", "").replace(")/", ""), 10));

		var date = new Date(val);
		//如果是1900年，则代表数据库数据为空
		if (date.getFullYear() == 1900) {
			return '';
		}
		//月份为0-11，所以+1，月份小于10时补个0
		var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
		var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
		var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
		var min = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
		var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
		if ((date.getFullYear() + "-" + month + "-" + currentDate + " " + hour + ":" + min + ":" + s) == "1-01-01 08:00:00") {
			return '';
		}
		else {
			return date.getFullYear() + "-" + month + "-" + currentDate + " " + hour + ":" + min + ":" + s;
		}
	}
	return '';
}

/**
 * 根据权限显示按钮
 * @param  {string} btnParent 将btn添加到的元素ID
 * @param  {string} type 默认top; 只有left、top、right、bottom：按钮显示位置
 * @return 循环按钮添加到btnParent元素
 */
function showBtn(type){
    var btns = getQueryString('btn'),result='';
    if(btns){
        var btn=btns.split('-');
        for(var i=0; i<btn.length;i++){
            var item= btn[i].split('_');
            if(item[1]==(type||'top')){
               result += '<a class="btn btn-info '+(type=='right' ? 'btn-xs' : 'btn-sm')+'" onclick="'+item[2]+'();">'+item[0]+'</a>&nbsp;';
            }
        }
    }
    return result;
}

/**
 * 数组去重
 * @param  {Array} arr 需要去重的数组
 * @return {Array}    去重后的数组
 */
function unique(arr) {
	var result = [];
	if(Object.prototype.toString.call(arr) === '[object Array]'){
		var hash = {},
			len = arr.length;
		for (var i = 0; i < len; i++){
			if (!hash[arr[i]]){
				hash[arr[i]] = true;
				result.push(arr[i]);
			}
		}
	}else{
		console.error('请输入一个数组');
	}
	return result;
}



/**
 * 正则验证
 * @param  {string/number} val  要验证的值
 * @param  {string} type 要验证的类型；email/url/mobile/phone/qq/ip/chinese/idcard/number/
 * @return {bool}      true/false
 */
function validator(val,type){
	var regexStr= {
		//邮箱正则
		email: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i,
		//url 地址正则
		url: /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
		//移动手机号码
		mobile: /^(14[7]|13[0-9]|15[0-9]|18[0-9]|17[0-9])\d{8}$/,
		//座机电话号码
		phone: /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/,
		//QQ验证正则
		qq: /^[1-9]\d{4,9}$/,
		//ip地址验证
		ip: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
		//汉字验证(有瑕疵，生僻字验证不全，努力更新中....)
		chinese: /^[\u4e00-\u9fa5]+$/,
		//身份证正则
		idcard: /^(\d{6})(18|19|20)?(\d{2})([01]\d)([0123]\d)(\d{3})(\d|X)?$/gi,
		//数字
		nodigits: /^\d+$/,
		number: /(^[1-9]\d*$)|(^([1-9]\d*|0)(\.\d*)?$)/,
        twoDecimalPlaces: /(^[1-9]\d*$)|(^([1-9]\d*|0)(\.\d{1,2}})?$)/,
		isInt: /^([1-9][0-9]*)|0$/,
		date: /Invalid|NaN/,
        //两位小数
        twoDecimalPlaces: /^-?\d+\.?\d{0,2}$/,
         //除特殊字符以外 （不能输入特殊字符的验证）
        nonSpecial:/^([a-zA-Z0-9\u4e00-\u9fa5]+)$/,
        //nonSpecial2:/^([a-zA-Z0-9-\u4e00-\u9fa5]+)$/, //允许连接符-出现

        //允许  汉字”、“字母”、“数字”、“_”、“-”、“空格” 验证
        nonSpecial2:/^([a-zA-Z0-9\s_\u4e00-\u9fa5-]+)$/,

        //银交所系统特有的数字验证
        //sseSpecial: /^-?\d{1,10}\.?\d{0,2}$/,
        sseSpecial: /^\d{1,8}(\.\d{1,2})?$/,//点前8 点后2, 12345678.00
        sseSpecial2: /^\d{1,2}(\.\d{1,2})?$/,//点前2 点后2, 10.00
        sseSpecial3: /^[1-9]\d{0,5}$/,//1-6位整数
        sseSpecial4: /^\d{1,17}(\.\d{1,2})?$/,//点前17 点后2 ，10000000000000000.00

        //sseSpecial2:/^\d{1,7}((\d{1,3})?|(\.\d{1,2})?|(\d{1}\.\d{1})?)$/  //长度1-10，（或者小数点前7位，小数点后2位，点前8点后1） 可以用这个


	};

	return regexStr[type].test(val);
}


/**
 *   自定义日期显示框
 *   id      需要添加日期选择框的dom元素
 *   status  使用方法的位置，日期框成对出现，前者'start'，后者'end'
 */
function customLayDate(id,status){
	laydate({
		elem: '#'+id,
		event: 'click',
		format: 'YYYY-MM-DD hh:mm:ss',
		istime: true,
		isclear: true,
		istoday: true,
		issure: true,
		choose: function(datas){
			if(status == 'start') return false;
			if(datas.substr(11) == '00:00:00') {
				datas = datas.replace('00:00:00', '23:59:59');
			}
			document.getElementById(id).value = datas;
		}
	});
}

/**
 * 扩展原生Date对象，添加format方法
 * @param  {string} format [格式化类型]
 * @return {[type]}        [description]
 */
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "H+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};

/**
 * 统一设置错误信息
 * @param  {[{code:'',msg:''}]}   codeObj     [返回的代码]
 * @param  {[type]}   msg      [返回的信息]
 * @param  {Function} callback [回调函数]
 * @param  {boolean} showAlert [是否显示提示信息]
 * @return {[type]}            [description]
 */
function checkResultCode(codeObj,msg,showAlert,closeParent,callback){
    var msgStr = codeObj.msg == 'success' ? msg : codeObj.msg;
    if(codeObj.code == webConfig.code.SUCCESS){
        if(callback && typeof callback == 'function'){
            callback();
        }
        if(showAlert){
            parent.layer.alert(msgStr,{icon:1},function(thisIndex){
                if(closeParent){
                    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    parent.layer.close(index); //再执行关闭
                }
                parent.layer.close(thisIndex);
            });
        }
    }else if(codeObj.code == webConfig.code.LOGIN_FIRST){
        parent.layer.msg(msgStr,function(){
            top.location.href="/login.html";
        });
    }else{
        parent.layer.alert(msgStr,{icon:2});
    }
}


$.fn.extend({
    /* 选项卡切换 */
    /* 调用示例：
     * $(selecter).tabsSwop({
     *     event:'click',
     *     listDoc:selecterList,
     *     animate:{argument:{property:value},speed:500,callback:function(obj){}},
     *     callback:function(obj){},
     *     attr:数字 或者 {property:'',value:''}
     * });
     */
    tabsSwop: function(options) {
        var _index = -1,
            defaultVal = {
                event: 'mouseover', //mouseover / click
                listDoc: '', //要显示/隐藏的元素
                selfCss: '', //自身样式变化
                animate: null, //切换的动画效果
                callback: null, //回调函数
                attr: 0 //默认选中项 如果是数字，则是下标，否则是自定义的属性
            },
            parentDoc = this.parent();

        defaultVal = $.extend(defaultVal, options);
        $(this).on(defaultVal.event, function() {
            _index = $(this).index();
            $(this).addClass(defaultVal.selfCss).siblings().removeClass(defaultVal.selfCss);
            if (defaultVal.callback && typeof defaultVal.callback == "function") {
                defaultVal.callback.call(this,defaultVal);
            }
            if (defaultVal.animate && typeof defaultVal.animate.callback == "function") {
                if($(defaultVal.listDoc).children().eq(_index).is(':visible')){return false;}
                $(defaultVal.listDoc).animate(defaultVal.animate.argument, defaultVal.animate.speed, function() {
                    defaultVal.animate.callback.call($(defaultVal.listDoc),_index);
                });
            }
            else{$(defaultVal.listDoc).children().eq(_index).show().siblings().hide();}
        });
        if (defaultVal.attr>=0){
            $(defaultVal.listDoc).children().hide();
            $(this).removeClass(defaultVal.selfCss);
            if ((typeof defaultVal.attr) == "number") {
                $(this).eq(defaultVal.attr).trigger(defaultVal.event);
            }
        }
    }
});

/**
 * [toCurrency description]
 * @param  {[type]} n [description]
 * @return {[type]}   [description]
 */
function toCurrency (n) {
    var fraction = ['角', '分'];
    var digit = [
        '零', '壹', '贰', '叁', '肆',
        '伍', '陆', '柒', '捌', '玖'
    ];
    var unit = [
        ['元', '万', '亿'],
        ['', '拾', '佰', '仟']
    ];
    var head = n < 0 ? '欠' : '';
    n = Math.abs(n);
    var s = '';
    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    n = Math.floor(n);
    for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
    }
    return head + s.replace(/(零.)*零元/, '元')
        .replace(/(零.)+/g, '零')
        .replace(/^整$/, '零元整');
}

/**
 * 将时间戳转化为日期
 * @param  {[type]} timestamp [description]
 * @param  {[type]} format    [description]
 * @return {[type]}           [description]
 */
function timestampToDate(timestamp,format){
    var temp = new Date(timestamp);
    if(format){
        return temp.format(format);
    }else{
        return temp;
    }
}

/**
 * 设置下拉列表数据
 * @param {[string]} eleId      [绑定的下拉列表元素]
 * @param {[Array]} data       [绑定的数据]
 * @param {[string]} defaultVal       [默认值]
 * @param {[{text:'',value:''}]} keyObj       [绑定的键]
 * @param {[type]} defaultVal [绑定的默认值]
 */
function setSelectOptions(eleId,data,defaultVal,keyObj) {
    if(document.getElementById(eleId)){
        var ele = document.getElementById(eleId);
        if(data){
            var options = {
                text:'text',
                value:'value'
            };
            if(keyObj){
                $.extend(options,keyObj);
            }
            for(var i=0; i < data.length; i++){
                ele.options.add(new Option(data[i][options.text],data[i][options.value]));
            }
        }else{
            console.error('数据为空');
        }

        if(defaultVal){
            for(var j=0; j < ele.options.length;j++){
                if(defaultVal == ele.options[j].value){
                    ele.options[j].selected = true;
                    break;
                }
            }
        }

    }else{
        console.error('元素不存在');
    }
}

/**
 * 修改jqGrid分页为自定义样式
 * @param  {[type]} table [列表]
 * @return {[type]}       [description]
 */
function updatePagerIcons(table) {
    var replacement =
    {
        'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
        'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
        'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
        'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
    };
    $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
        var icon = $(this);
        var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
        if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
    });
    setIframeHeight();
}
/**
 * 设置iframe高度
 */
function setIframeHeight(){
    $('#mainFrame', window.parent.document).height($('body').height());
    // document.documentElement.scrollHeight
}
/**
 * 根据值获取文本
 * @param  {[array]} arr        [数组]
 * @param  {[string]} val [value值]
 * @return {[type]}            [对应的文本]
 */
function getTextByValue(arr,val){
    if(arr && arr.length){
        var str ='';
        for(var i=0;i<arr.length;i++){
            if(arr[i].value == val){
                str = arr[i].text;
                break;
            }
        }
        return str;
    }else{
        console.error('数组不能为空');
    }
}

/**
 * 根据编码获取状态
 * @param  {[string]} code [编码]
 * @return {[Array]}      [状态列表]
 */
function getStatusByCode(code){
    var arr = [];
    $.ajax({
        url: webConfig.webUrl + '/dict/queryDictInfo',
        type: 'POST',
        dataType: 'json',
        data: {code: code},
        async: false,
        success: function(data){
            if(data && data.result){
                arr = data.result;
            }
        }
    });
    return arr;
}

/**
 * 回车确认
 * @param {Function} callback [description]
 */
function bodyKeyDown(callback){
    $("body").keydown(function (ev) {
        var event = ev || event;
        if (event.keyCode == "13") {
            if(callback && typeof callback == 'function'){
                callback();
            }
        }
    });
}


(function($){
    //备份jquery的ajax方法
    var _ajax=$.ajax;
    $.ajax=function(opt){
        if(opt && opt.data && opt.data){
            for(var item in opt.data){
                opt.data[item] = $.trim(opt.data[item]);
            }
        }
        return _ajax(opt);
    };
})(jQuery);

/**
 * 避免数字计算精度误差
 * @param {Function} callback [description]
 * 例：alert(0.1 + 0.2 === 0.3); ==> false;
 *     alert(Math.formatFloat(0.1 + 0.2, 1) === 0.3); ==》 true;
 */
Math.formatFloat = function(f, digit) {
    digit = digit || 1;
    var m = Math.pow(10, digit);
    return (f * m).toFixed(2) / m;
};


// (() => {
//     $('input[data-currency="1"]').change(function(){
//         debugger;
//         var _this = $(this);
//         var val = parseFloat(_this.val()),
//             p = _this.closest('.form-group'),
//             h = p.find('.help-block');
//         if(val){
//             p.addClass('has-info');
//             h.html(toCurrency(val));
//         }else{
//             p.removeClass('has-info');
//             h.html('');
//         }
//     });
// })();

/**
 * 判断是否存在
 * @param  {[string]} str [要判断的值]
 * @param  {[string]} num [值]
 * @return {[string]}     [对应的文本]
 */
function isExist(str, num){
    num = (num===0?'0':num) || '';
    return str?str:num;
}



/**
 * 判断字符串的长度
 * @param  {[string]} str [要判断的值]
 * @return {[string]}     [对应的长度]
 */
 function getLength(str)
{
    var realLength = 0;
    for (var i = 0; i < str.length; i++)
    {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128)
        realLength += 1;
        else
        realLength += 2;
    }
    return realLength;
}
/**
 * 转换时间
 * @param {[type]} dateStr 时间值
 * @param {[type]} type  类型
 */
function setTime(dateStr,type){
    return new Date(dateStr+(type?" 23:59:59":" 00:00:00")).getTime();
}
/**
 * 表单验证
 * @param  {[type]} inputId   验证的inputId
 * @param  {[type]} errorId   错误信息提示元素id
 * @param  {[type]} errorFlag 是否有错误信息
 * @param  {[type]} errorMes  错误信息
 * @return {[type]}           [description]
 */
function checkInput(inputId,errorId,errorFlag,errorMes){
    errorFlag?$("#"+inputId).closest('.form-group').addClass('has-error'):$("#"+inputId).closest('.form-group').removeClass('has-error');
    errorMes?$('#'+errorId).html(errorMes):$('#'+errorId).html("");
}

